import storage from './storage'
import { toast, showLoading, hideLoading } from './util'
let config = {
  apiUrl: `${getApp().globalData.server}`,
  clickLock: false,
}

/**
 * @param {*} url 
 * @param {*} params 
 * @param {*} methods 
 * @param {*} isFormData 
 */

const request = (url, params, methods, isFormData = true) => {
  return new Promise((resolve, reject) => {
    if(methods === 'GET') {
      showLoading()
    } else {
      if (config.clickLock) {
        return false;
      } else {
        config.clickLock = true;
      }
      showLoading('提交中...')
    }
    wx.request({
      url: `${config.apiUrl}${url}`,
      method: methods || 'POST',
      data: params,
      timeout: 12000,
      header: {
        "Authorization": `Bearer ${storage.get('token')}`,
        "clientid": `${getApp().globalData.clientId}`,
        'content-type': isFormData ? 'application/x-www-form-urlencoded' : 'application/json',
      },
      success(res) {
        config.clickLock = false;
        if (res.statusCode === 200) {
          if(methods === 'GET') {
            hideLoading()
          }
          if(res.data.code === 200) {
            resolve(res.data)
            hideLoading()
          }
          else if(res.data.code === 401) {
            let token = storage.get('token') ? 'expire' : 'none';
            notLogin(token)
          }
          else {
            toast(res.data.msg)
          }
        } else {
          toast("服务器错误:" + res.code);
        }
      },
      fail: function (res) {
        config.clickLock = false;
        if (res.errMsg === "request:fail timeout") {
          toast('请求超时')
        } else {
          hideLoading();
        };
      },
    })
  })
}

const notLogin = (str) => {
  let tips = str === 'none' ? "请登录" : '登录超时，请重新登录！'
  //未登录
  wx.showModal({
    title: '提示',
    content: tips,
    success(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/login',
          });
        } else if (res.cancel) {
          hideLoading()
        };
    }
  });
}
function naviBack() {
  let pages = getCurrentPages();
  if (pages.length > 1) {
    wx.navigateBack({
      delta: 1,
    });
  } else {
    console.log("当前页没有可以返回的页面")
  };
}

const http = {
  get: (url, data, isFormData) => {
    return request(url, data, 'GET', isFormData,)
  },
  post: (url, data, isFormData) => {
    return request(url, data, 'POST', isFormData,)
  },
  put: (url, data, isFormData) => {
    return request(url, data, 'PUT', isFormData)
  },
  del: (url, data, isFormData) => {
    return request(url, data, 'DELETE', isFormData)
  },
}
export {
  http
}